import React, { useState } from "react";
import { 
  StyleSheet, 
  Text, 
  View, 
  TouchableOpacity,
  ScrollView,
  Platform,
  TextInput
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Image } from "expo-image";
import { Camera, Upload, Volume2, Copy, Translate } from "lucide-react-native";
import { colors } from "@/constants/colors";
import { Button } from "@/components/Button";
import { Card } from "@/components/Card";

export default function OCRScreen() {
  const [image, setImage] = useState<string | null>(null);
  const [recognizedText, setRecognizedText] = useState<string | null>(null);
  const [translatedText, setTranslatedText] = useState<string | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [isTranslating, setIsTranslating] = useState(false);

  // Mock function to simulate taking a photo
  const handleTakePhoto = async () => {
    // In a real app, we would use expo-image-picker to take a photo
    setIsProcessing(true);
    
    // Simulate delay
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // Use a sample image from Unsplash
    setImage("https://images.unsplash.com/photo-1456081101716-74e616ab23d8?ixlib=rb-1.2.1&auto=format&fit=crop&w=1024&q=80");
    
    // Simulate OCR processing
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // Set mock recognized text
    setRecognizedText("The quick brown fox jumps over the lazy dog.");
    
    setIsProcessing(false);
  };

  // Mock function to simulate picking an image from gallery
  const handlePickImage = async () => {
    // In a real app, we would use expo-image-picker to pick an image
    setIsProcessing(true);
    
    // Simulate delay
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // Use a sample image from Unsplash
    setImage("https://images.unsplash.com/photo-1544716278-ca5e3f4abd8c?ixlib=rb-1.2.1&auto=format&fit=crop&w=1024&q=80");
    
    // Simulate OCR processing
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // Set mock recognized text
    setRecognizedText("Hello world! This is a sample text for OCR demonstration.");
    
    setIsProcessing(false);
  };

  // Mock function to simulate translation
  const handleTranslate = async () => {
    if (!recognizedText) return;
    
    setIsTranslating(true);
    
    // Simulate translation delay
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // Set mock translated text
    setTranslatedText("你好世界！这是一个OCR演示的示例文本。");
    
    setIsTranslating(false);
  };

  // Mock function to simulate text-to-speech
  const handleSpeak = () => {
    // In a real app, we would use expo-speech to speak the text
    console.log("Speaking:", recognizedText);
  };

  // Mock function to simulate copying text to clipboard
  const handleCopy = () => {
    // In a real app, we would use expo-clipboard to copy the text
    console.log("Copied to clipboard:", recognizedText);
  };

  return (
    <SafeAreaView style={styles.container} edges={["top"]}>
      <ScrollView style={styles.scrollView} contentContainerStyle={styles.scrollContent}>
        <Text style={styles.title}>Text Recognition</Text>
        <Text style={styles.subtitle}>
          Take a photo or upload an image to extract text
        </Text>

        <View style={styles.imageContainer}>
          {image ? (
            <Image
              source={{ uri: image }}
              style={styles.image}
              contentFit="cover"
            />
          ) : (
            <View style={styles.placeholderImage}>
              <Camera size={48} color={colors.text.tertiary} />
              <Text style={styles.placeholderText}>
                No image selected
              </Text>
            </View>
          )}
        </View>

        <View style={styles.buttonContainer}>
          <Button
            title="Take Photo"
            onPress={handleTakePhoto}
            variant="primary"
            style={styles.button}
            leftIcon={<Camera size={20} color={colors.text.inverse} />}
            isLoading={isProcessing}
          />
          <Button
            title="Upload Image"
            onPress={handlePickImage}
            variant="outline"
            style={styles.button}
            leftIcon={<Upload size={20} color={colors.primary} />}
            isLoading={isProcessing}
          />
        </View>

        {isProcessing && (
          <Card style={styles.processingCard}>
            <Text style={styles.processingText}>Processing image...</Text>
          </Card>
        )}

        {recognizedText && !isProcessing && (
          <>
            <Card style={styles.textCard}>
              <View style={styles.cardHeader}>
                <Text style={styles.cardTitle}>Recognized Text</Text>
                <View style={styles.cardActions}>
                  <TouchableOpacity style={styles.actionButton} onPress={handleSpeak}>
                    <Volume2 size={20} color={colors.primary} />
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.actionButton} onPress={handleCopy}>
                    <Copy size={20} color={colors.primary} />
                  </TouchableOpacity>
                </View>
              </View>
              <Text style={styles.recognizedText}>{recognizedText}</Text>
            </Card>

            <Button
              title="Translate to Chinese"
              onPress={handleTranslate}
              variant="secondary"
              style={styles.translateButton}
              leftIcon={<Translate size={20} color={colors.text.primary} />}
              isLoading={isTranslating}
            />

            {translatedText && (
              <Card style={styles.textCard}>
                <View style={styles.cardHeader}>
                  <Text style={styles.cardTitle}>Chinese Translation</Text>
                  <View style={styles.cardActions}>
                    <TouchableOpacity style={styles.actionButton} onPress={handleSpeak}>
                      <Volume2 size={20} color={colors.primary} />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.actionButton} onPress={handleCopy}>
                      <Copy size={20} color={colors.primary} />
                    </TouchableOpacity>
                  </View>
                </View>
                <Text style={styles.translatedText}>{translatedText}</Text>
              </Card>
            )}
          </>
        )}

        {/* Web compatibility notice */}
        {Platform.OS === "web" && (
          <Text style={styles.webNotice}>
            Note: Camera functionality is limited on web. For the full experience, please use a mobile device.
          </Text>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 16,
    paddingBottom: 100, // Add extra padding to prevent content from being hidden by tab bar
  },
  title: {
    fontSize: 24,
    fontWeight: "700",
    color: colors.text.primary,
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
    color: colors.text.secondary,
    marginBottom: 24,
  },
  imageContainer: {
    aspectRatio: 4/3,
    borderRadius: 12,
    overflow: "hidden",
    backgroundColor: colors.card,
    marginBottom: 16,
  },
  image: {
    width: "100%",
    height: "100%",
  },
  placeholderImage: {
    width: "100%",
    height: "100%",
    justifyContent: "center",
    alignItems: "center",
  },
  placeholderText: {
    marginTop: 12,
    fontSize: 16,
    color: colors.text.tertiary,
  },
  buttonContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 24,
  },
  button: {
    flex: 1,
    marginHorizontal: 4,
  },
  processingCard: {
    marginBottom: 16,
  },
  processingText: {
    fontSize: 16,
    color: colors.text.secondary,
    textAlign: "center",
  },
  textCard: {
    marginBottom: 16,
  },
  cardHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 8,
  },
  cardTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: colors.text.primary,
  },
  cardActions: {
    flexDirection: "row",
  },
  actionButton: {
    padding: 4,
    marginLeft: 8,
  },
  recognizedText: {
    fontSize: 16,
    color: colors.text.primary,
    lineHeight: 24,
  },
  translatedText: {
    fontSize: 16,
    color: colors.text.primary,
    lineHeight: 24,
  },
  translateButton: {
    marginBottom: 16,
  },
  webNotice: {
    fontSize: 14,
    color: colors.text.tertiary,
    fontStyle: "italic",
    textAlign: "center",
    marginTop: 16,
  },
});